package middleware

import (
	"gitee.com/gopher2011/gin"
	jwt "gitee.com/gopher2011/gin-jwt"
	"gitee.com/gopher2011/mall/app/dao"
	"gitee.com/gopher2011/mall/app/service"
	"net/http"
	"time"
)

// 跨域
func Cors() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 设置允许访问域名
		ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		// 设置缓存时间
		ctx.Writer.Header().Set("Access-Control-Max-Age", "86400")
		// 允许请求方法
		ctx.Writer.Header().Set("Access-Control-Allow-Methods", "*")
		// 允许请求头信息
		ctx.Writer.Header().Set("Access-Control-Allow-Headers", "*")
		// 允许客户端携带验证头信息,如: Cookies token
		ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		// 如果请求是Option 返回200
		if ctx.Request.Method == http.MethodOptions {
			ctx.AbortWithStatus(200)
		} else {
			// 否则向下继续判定
			ctx.Next()
		}
	}
}

// 指定加密密钥
var identityKey = "id"

func Jwt() (*jwt.JWTMiddleware, error) {
	auth, err := jwt.New(&jwt.JWTMiddleware{
		Realm:       "test zone",
		Key:         []byte("secret key"),
		Timeout:     time.Hour,
		MaxRefresh:  time.Hour,
		IdentityKey: identityKey,
		PayloadFunc: func(data interface{}) jwt.MapClaims {
			if v, ok := data.(*dao.UmsAdmin); ok {
				return jwt.MapClaims{
					identityKey: v.Username,
				}
			}
			return jwt.MapClaims{}
		},

		IdentityHandler: func(c *gin.Context) interface{} {
			claims := jwt.ExtractClaims(c)
			return &dao.UmsAdmin{
				Username: claims[identityKey].(string),
			}
		},

		AuthFunc: func(c *gin.Context) (interface{}, error) {
			var l dao.UmsJWTParma
			if err := c.Parse(&l); err != nil {
				return "", jwt.ErrMissingLoginValues
			}
			info, err := service.UmsAdmin.Login(&l)
			if err != nil {
				return nil, err
			}
			return &dao.UmsAdmin{
				Username: info.Username,
			}, nil
		},

		AuthAfter: func(data interface{}, c *gin.Context) bool {
			var l dao.UmsJWTParma
			info, err := service.UmsAdmin.Login(&l)
			if err != nil {
				return false
			}
			if v, ok := data.(*dao.UmsAdmin); ok && v.Username == info.Username {
				return true
			}

			return false
		},

		UnAuthFunc: func(c *gin.Context, code int, message string) {
			c.JSON(code, gin.H{
				"code":    code,
				"message": message,
			})
		},
	})
	if err != nil {
		return nil, err
	}
	return auth, nil
}

//r.POST("/login", auth.LoginHandler)
//
//r.NoRoute(auth.MiddlewareFunc(), func(c *gin.Context) {
//	claims := jwt.ExtractClaims(c)
//	log.Printf("NoRoute claims: %#v\n", claims)
//	c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
//})
//
//g := r.Group("/auth")
//// 刷新时间可以长于 token的timeout
//g.GET("/refresh_token", auth.RefreshHandler)
//g.Use(auth.MiddlewareFunc())
//{
//g.GET("/hello", helloHandler)
//}
